<?php
namespace app\workerman;



use app\common\entity\Config;
use app\common\entity\GameLoginLog;
use app\common\entity\GameRoomLog;
use app\common\entity\GameUserLog;
use app\common\entity\GoodsOrders;
use app\common\entity\Image;
use app\common\entity\Mywallet;
use app\common\entity\MywalletLog;
use app\common\entity\Orders;
use app\common\entity\Video;
use app\common\shop\OrderModel;
use app\common\shop\UserLevelModel;
use GatewayWorker\Lib\Gateway;
use app\common\entity\GameRoom;
use Workerman\Lib\Timer;
use app\common\entity\User;
use think\Db;
use app\workerman\Robot;

class Game extends Attached
{


    /**
     * 用户登陆websocket
     * @param $uid
     * @param $list
     */
    public function login($client_id,$uid,$ordersn,$token){


        //获取用户信息存缓存并send给用户
        $userinfo = $this->getInfo($uid);
        if(!$userinfo){
            Gateway::sendToClient($client_id,errorSend('login',1,'用户信息错误'));
            return false;
        }


        /*//判断游戏是否开启
        if($this->getConfigGroup('game','game_switch') != 1 && $uid != 114 && $uid !=115){
            Gateway::sendToClient($client_id,errorSend('checkRoomLog',1,'游戏正在维护'));
            return;
        }*/
        //判断是否已经登陆
        /*if(!Gateway::isUidOnline($uid)) {*/

        Gateway::bindUid($client_id, $uid);
        Gateway::updateSession($client_id, ['status' => 0,'ordersn'=>$ordersn,'client_id'=>$client_id,'uid'=>$uid]);
        $_SESSION['client_id'] = $client_id;
        $_SESSION['uid'] = $uid;


        GameLoginLog::where( 'client_id' , $client_id)->delete();
        GameLoginLog::insert(['user_id' => $uid, 'ordersn' => $ordersn, 'client_id' => $client_id]);
        $orderMoney = Db::name('shop_order')->where('ordersn',$ordersn)->sum('total');

        $one_room = GameRoom::where('money','<=',$orderMoney)->order('size desc')->find();

        $arrr = GameRoom::where('money',$orderMoney)->select();


        foreach ($arrr as $k => $v) {
            $redisInfo = $this->redis_hGet('1225blz_roominfo',$v['id']);
            if($redisInfo){
                $v['count'] = isset($redisInfo['users'])?count($redisInfo['users']):0;
            }else{
                $info = [
                    'num'=>1,
                    'users'=>[],
                ];
                $this->redis_hSet('1225blz_roominfo',$v['id'],$info);//存入redis
                $v['count'] = 0;
            }

        }

        $pai = User::alias('u')
            ->join('game_user_log l','l.uid = u.id')
            ->join('game_room r','r.id = l.room_id')
            ->field('u.nick_name,u.id,u.avatar,count(l.id) as count')
            ->where('r.size',$one_room['size'])
            ->group('u.id')
            ->order('count desc')
            ->limit(3)
            ->select();
        #@todo  排行榜
        $img = Image::where('types',2)->select();
        Gateway::sendToClient($client_id, successSend('img', '登陆成功', toArray($img)));
        Gateway::sendToClient($client_id, successSend('ranking', '登陆成功', toArray($pai)));
        Gateway::sendToClient($client_id, successSend('login', '登陆成功', toArray($arrr)));
        /* }*/
    }

    #进入房间
    public function RoomIn($client_id,$room_id){

        if(!Gateway::getUidByClientId($client_id)){
            return false;
        }

        $roomInfo = GameRoom::where('id',$room_id)->find();
        if($roomInfo['status'] == 1){
            Gateway::sendToClient($client_id,errorSend('roomin',1,'房间正在运行'));
            return false;
        }
        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
        if(!isset($room_redis['users']) || count($room_redis['users']) >= 10){
            Gateway::sendToClient($client_id,errorSend('roomin',1,'房间已满'));
            return false;
        }
        $in_room = false;
        foreach($room_redis['users'] as $k=>$v){
            if($v['uid'] == Gateway::getUidByClientId($client_id)){
                $in_room = true;
            }
        }



        Gateway::joinGroup($client_id,$room_id);

        if(!$in_room == true){
            User::where('id',Gateway::getUidByClientId($client_id))->update(['game_status'=>1]);
            $in_user = ['uid'=>Gateway::getUidByClientId($client_id),'robot'=>0,'status'=>1,'award'=>0];
            array_push($room_redis['users'],$in_user);
            $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);
        }



        $roomUserArr = [];

        foreach($room_redis['users'] as $k=>$v){
            $roomUserArr[] = $this->getInfo($v['uid']);
        }


        $video = Video::where('id',$roomInfo['video'])->find();
        Video::where('id',$video['id'])->setInc('click_num');
        $goods = Db::name('shop_goods')->where('id',$roomInfo['goods_id'])->find();
        $path = unserialize($goods['path']);
        $goods['path'] = $path;
        $goods['img'] = $path[0];
        Gateway::sendToClient($client_id,successSend('roomin','进入房间',[
            'title'=>$roomInfo['name'],
            'goods'=>$goods,

            'video'=>$video['ts'],


            'user'=>$roomUserArr,
            'this_user'=>Gateway::getUidByClientId($client_id)
        ]));

        Gateway::sendToGroup($room_id,successSend('userjoin','用户进房',$roomUserArr));



        $this->roomchange();


        //@todo 30秒开始
        $this->thirty($room_id);
    }

    public function thirty($room_id){
        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
        if(isset($room_redis['thirty']) && $room_redis['thirty'] == true)return false;
        $ready_time = 30;
        $room_redis['thirty'] = true;
        $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);

        $rand = $this->randomDivInt(10-count($room_redis['users']),$ready_time);

        foreach($rand as $k=>$v) {
            if ($k != 0) {
                $rand[$k] += $rand[$k - 1];
            }
        }
        $descTime = 0;
        $key = 0;
        $num = 2;

        $timer_id = Timer::add(0.5,function(&$timer_id,&$room_id,&$descTime,&$rand,&$key,&$num,&$ready_time){


            $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);

            //检测人员是否齐全
            $is_member = 0;
            foreach($room_redis['users'] as $k=>$val){
                if(isset($val['robot']) && $val['robot'] == 0){
                    $is_member++;
                }
            }

            if($is_member <= 0){
                $info = GameRoom::where('id',$room_id)->find();
                foreach ($room_redis['users'] as $k=>$val){
                    if($k+1 >= $info['num']){
                        echo $k."\n\n";
                        unset($room_redis['users'][$k]);
                    }
                }
                $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);
                Timer::del($timer_id);
                return false;
            }



            $descTime = bcadd($descTime,0.5,2);






            if(isset($room_redis['users']) && count($room_redis['users']) < 10 &&isset($rand[$key]) && $rand[$key] <= $descTime){

                $key++;
                $user = $this->getOrderRand();

                $robot = new \app\workerman\Robot();
                $robot->robotRoomIn($user['id'],$room_id);

                //array_splice($rand,0,1);
            }

            $num--;
            if($num <= 0){
                $num = 2;
                Gateway::sendToGroup($room_id,successSend('ready_time','用户进房',['room_id'=>$room_id,'time'=>number_format($ready_time-$descTime)]));
            }

            if(number_format($descTime,1) == ($ready_time+0.5)){
                $room_redis['thirty'] = false;
                $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);
                echo "startGame\n";
                $this->is_start_game($room_id,$room_redis['num']);
                Timer::del($timer_id);
            }


        },[&$timer_id,&$room_id,&$descTime,&$rand,&$key,&$num,&$ready_time]);

    }
    public function getOrderRand(){

        $user = User::where('robot', 1)->where('status', 1)->where('game_status', 0)->order('id desc')->select();
        $keys = array_rand(json_decode(json_encode($user),true),1);
        return $user[$keys];

    }
    //检测游戏开始
    public function is_start_game($room_id,$num){
        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
        $roomInfo = GameRoom::where('id',$room_id)->find();

        if($roomInfo['status'] == 1){
            return false;
        }
        if(count($room_redis['users']) < 10){
            return false;
        }
        if($num == 2){
            $room_redis['num'] = 2;
        }
        #倒计时  开始
        GameRoom::where('id',$room_id)->update(['status'=>1]);

        # 这里先存库room_log
        $log_id = GameRoomLog::addNew($this->redis_hGet('1225blz_roominfo',$room_id),$room_id,$num);
        $room_redis['log_id'] = $log_id;
        $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);
        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);


        $descTime = 3;
        if($room_redis['num'] == 2){
            $this->playGame($room_id);
            return false;
        }
        $timer_id = Timer::add(1,function(&$timer_id,&$room_id,&$descTime){
            //检测人员是否齐全
            $roomInfo = GameRoom::where('id',$room_id)->find();
            if($roomInfo['status'] != 1){
                Timer::del($timer_id);
                return false;
            }

            Gateway::sendToGroup($room_id,successSend('start_game','倒计时',['time'=>$descTime]));
            if($descTime <= 0){
                Timer::del($timer_id);
                $this->playGame($room_id);
                return false;
            }



            $descTime--;
        },[&$timer_id,&$room_id,&$descTime]
        );
    }

    //游戏开始了
    public function playGame($room_id){
        $roomInfo = GameRoom::where('id',$room_id)->find();
        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
        //检测人员是否齐全
        $roomInfo = GameRoom::where('id',$room_id)->find();
        if($roomInfo['status'] != 1){
            return false;
        }


        //奖励和出局的人
        $changeUser = self::get_award($room_id,isset($room_redis['users'])?$room_redis['users']:[],$room_redis['num']);

        foreach($changeUser['arr'] as $k=>$v){
            if($v['status'] == 2){
                Gateway::sendToGroup($room_id,successSend('this_out','这人出局了',['out'=>$changeUser['out']]));
            }
        }

        $room_redis['users'] = $changeUser['arr'];
        $robot = new \app\workerman\Robot();
        if(!$robot->is_robot($changeUser['out']['uid'])){
            $clientInfo = $this->getClientInfoByUid($changeUser['out']['uid']);
            $session = Gateway::getSession($clientInfo['client_id']);
            Db::name('shop_order')->where('ordersn',$session['ordersn'])->update(['playgame'=>1,'status'=>2]);
            /*$order = OrderModel::getOrdersnInfo($session['ordersn']);
            UserLevelModel::commssion($order);*/
        }
        $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);

        if($room_redis['num'] == 2){
            $this->result($room_id);
            return false;
        }
        //使用副卡     2020/12/21  经理说要有使用副卡的和不用使用副卡的都要有信息
        /*Gateway::sendToGroup($room_id,successSend('out','开奖结果',['out'=>$changeUser['out']]));*/

        $zqq = Timer::add(4,function(&$zqq,&$room_id,&$desc_time,&$changeUser){

            Timer::del($zqq);

            //检测人员是否齐全
            $roomInfo = GameRoom::where('id',$room_id)->find();
            if($roomInfo['status'] != 1){
                Timer::del($zqq);
                return false;
            }

            foreach($changeUser['arr'] as $k=>$v){
                if($v['robot'] == 1){continue;}
                if($v['status'] == 2){
                    Gateway::sendToUid($v['uid'],successSend('need_focas','请使用福卡',['out'=>$changeUser['out'],'msg'=>$changeUser['out']['nick_name'].'在考虑是否使用福卡复活']));
                    //机器人用福卡
                }else{
                    Gateway::sendToUid($v['uid'],successSend('dont_need_focas','不需要福卡',['out'=>$changeUser['out'],'msg'=>$changeUser['out']['nick_name'].'在考虑是否使用福卡复活']));
                }
            }
            $timer_idd = Timer::add(5,function(&$timer_idd,&$room_id,&$changeUser){

                Timer::del($timer_idd);
                $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
                //检测人员是否齐全
                $roomInfo = GameRoom::where('id',$room_id)->find();
                if($roomInfo['status'] != 1){
                    Timer::del($timer_idd);
                    return false;
                }
                foreach($changeUser['arr'] as $k=>$v){
                    if ($v['robot'] == 1 && $v['status'] = 2 && $changeUser['out']['uid'] == $v['uid']) {
                        $room_redis['users'][$k]['status'] = 1;
                        $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);
                        Gateway::sendToGroup($room_id, successSend('use_focas', '复活', ['msg' => $changeUser['out']['nick_name'] . '使用了福卡复活']));
                    }
                }

            },[&$timer_idd,&$room_id,&$changeUser]);







            $this->wole($room_id);



        },[&$zqq,&$room_id,&$desc_time,&$changeUser]);



    }

    public function wole($room_id){
        //选择福卡3s
        $desc_time = 7;
        $timer_id = Timer::add(1,function(&$timer_id,&$room_id,&$desc_time){
            $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
            //检测人员是否齐全
            $roomInfo = GameRoom::where('id',$room_id)->find();
            if($roomInfo['status'] != 1){
                Timer::del($timer_id);
                return false;
            }

            $use = true;
            foreach($room_redis['users'] as $k=>$v){
                if($v['status'] == 2 || isset($v['not_use'])){
                    $use = false;
                }
            }



            Gateway::sendToGroup($room_id,successSend('desc_tmie','倒计时',['time'=>$desc_time]));

            //if($desc_time === 0 || $use == true){
            if($desc_time === 0){
                $this->result($room_id);
                Timer::del($timer_id);
            }

            $desc_time--;


        },[&$timer_id,&$room_id,&$desc_time]);
    }
    public function result($room_id){
        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
        $room_log_redis = $this->redis_hGet('1225blz_room_log',$room_id);
        $this->redis_hSet('1225blz_room_log',$room_id,$room_redis);
        $is_out = false;
        $out_user = [];
        foreach($room_redis['users'] as $k=>$v){
            if($v['status'] == 2 && $v['robot'] != 1){
                $is_out = true;
                $out_user = $v;
            }
        }
        if($is_out == true){
            $timer_id = Timer::add(3,function(&$timer_id,&$room_id,&$out_user) {
                $this->GameOver($room_id,$out_user);
                Timer::del($timer_id);
            },[&$timer_id,&$room_id,&$out_user]);
        }else{
            $this->RoundTwo($room_id,$out_user);
        }

        #@todo   存库  给钱
        GameRoomLog::edit($room_log_redis,$room_id);
    }

    private function GameOver($room_id,$out_user = []){
        $info = GameRoom::where('id',$room_id)->find();
        if($info['status'] == 0){
            return false;
        }
        GameRoom::where('id',$room_id)->update(['status'=>0]);

        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
        $log_id = $room_redis['log_id'];


        $room_log_redis = $this->redis_hGet('1225blz_room_log',$room_id);

        $out_num = 0;

        foreach($room_redis['users'] as $k=>$v){
            if($v['robot'] == 0 && $v['status'] == 2){
                //出局
                $GameLoginLog = GameLoginLog::where('user_id',$v['uid'])->order('id desc')->find();


                $out_num = Db::name('shop_order')->where('ordersn',$GameLoginLog['ordersn'])->value('total');

                $update = User::where('id',$v['uid'])->update(['game_status'=>0]);

                if($update){

                    $room_redis['users'][$k]['status'] = 3;
                    unset($room_redis['users'][$k]);
                    $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);

                    $roomUserArr = [];
                    foreach($room_redis['users'] as $key=>$val){
                        $roomUserArr = $this->getInfo($v['uid']);
                    }

                    Gateway::sendToUid($v['uid'],successSend('out','出局',[]));//roomout
                    if($room_redis['num'] === 1) {
                        foreach ($room_redis['users'] as $k => $v) {
                            Gateway::sendToUid($v['uid'], successSend('nonuse_focas', '未使用福卡出局', ['msg' => $roomUserArr['nick_name'] . '未使用福卡', 'out' => $roomUserArr]));
                        }
                    }

                    # 修改订单状态 （判断游戏后修改）
                    Db::name('shop_order')->where('ordersn',$GameLoginLog['ordersn'])->update(['playgame'=>1,'status'=>2]);
                    $order = OrderModel::getOrdersnInfo($GameLoginLog['ordersn']);
                    UserLevelModel::commssion($order);

                    $this->focas_porfit($GameLoginLog['user_id']);
                    if($clientInfo = $this->getClientInfoByUid($v['uid'])){
                        Gateway::leaveGroup($clientInfo['client_id'],$room_id);
                    }

                }
            }

        }

        foreach($room_redis['users'] as $k=>$v){
            if($v['robot'] == 1){
                continue;
            }
            $award_config = bcmul(Config::getValue('game_award'),0.01,4);
            $award = bcmul($out_num,$award_config,4);
            $room_redis['users'][$k]['award'] = $award;
            Gateway::sendToUid($v['uid'],successSend('award','获得红包',['round'=>$room_redis['num'],'money'=>number_format($award,2)]));

            MywalletLog::addLog($v['uid'], number_format($award,2), 1, '抽奖奖励', 14, 1);
        }
        print_r($room_log_redis['users']);
        $sum_award = 0;
        foreach($room_log_redis['users'] as $k=>$v){
            if($v['status'] == 3)continue;

            /*foreach($room_redis['users'] as $key=>$val){
                if(isset($v['uid']) && isset($val['uid']) && $v['uid'] == $val['uid']){

                    $room_log_redis['users'][$k]['award'] = $val['award'];
                }
            }*/

            if($v['robot'] == 1)continue;
            $GameLoginLog = GameLoginLog::where('user_id',$v['uid'])->order('id desc')->find();
            $order_num = Db::name('shop_order')->where('ordersn',$GameLoginLog['ordersn'])->value('total');
            echo Db::name('shop_order')->getLastSql()."\n\n";

            $sum_award = bcadd($sum_award,$order_num,4);
            print_R([$v,$room_id,$log_id,$order_num,$GameLoginLog['ordersn']]);
            GameRoomLog::profit($v,$room_id,$log_id,$order_num,$GameLoginLog['ordersn']);
        }
        #  分红
        //GameRoomLog::room_rpofit($sum_award,$log_id);
        GameRoomLog::room_rpofit($out_num,$log_id);





        $over_time = Timer::add(3,function(&$over_time,&$room_id){
            Timer::del($over_time);
            $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);





            foreach($room_redis['users'] as $k=>$v){
                User::where('id',$v['uid'])->update(['game_status'=>0]);
                #@todo 匹配
                if($v['robot']!=1)$this->matching($v['uid'],$room_id);
            }

            Gateway::sendToGroup($room_id,successSend('game_over','GameOver',[]));

            $seesions =  Gateway::getClientSessionsByGroup($room_id);
            foreach($seesions as $k=>$v){
                Gateway::leaveGroup($v['client_id'],$room_id);
            }
            $info = [
                'num'=>1,
                'users'=>[],
            ];

            $this->redis_hSet('1225blz_roominfo',$room_id,$info);//存入redis


        },[&$over_time,&$room_id]);
    }
    private function RoundTwo($room_id,$out_user){

        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
        $room_redis['num'] = 2;
        $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);
        GameRoom::where('id',$room_id)->update(['status'=>0]);

        $video = Video::where('rand()')->find();
        if(count($room_redis['users']) == 10){
            $this->is_start_game($room_id,2);
            $num = 0;
            foreach($room_redis['users'] as $k=>$v){
                if($v['robot'] == 0){
                    $num++;
                }
            }
            //Video::where('id',$video['id'])->setInc('click_num',$num);
            Gateway::sendToGroup($room_id,successSend('round_two','',['video'=>$video['pic']]));
        }else{
            $this->GameOver($room_id,$out_user);
        }
    }
    /**
     * 是否使用福卡
     * @param $client_id
     * @param $status
     */
    public function focas($client_id,$room_id,$status){


        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
        //检测人员是否齐全
        $roomInfo = GameRoom::where('id',$room_id)->find();
        if($roomInfo['status'] != 1){
            return false;
        }
        $uid = Gateway::getUidByClientId($client_id);

        foreach($room_redis['users'] as $k=>$v){
            if($uid == $v['uid']){

                $mywallet = Mywallet::where('user_id',$uid)->find();

                if( $mywallet['focas'] <= 0){
                    /*unset($room_redis['users'][$k]);
                    $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);*/


                    # 修改订单状态 （判断游戏后修改）
                    $session = Gateway::getSession($client_id);
                    Db::name('shop_order')->where('ordersn',$session['ordersn'])->update(['playgame'=>1,'status'=>2]);
                   /* $order = OrderModel::getOrdersnInfo($session['ordersn']);
                    UserLevelModel::commssion($order);*/

                    $this->focas_porfit($session['uid']);


                    Gateway::leaveGroup($client_id,$room_id);
                    $roomUserArr = [];
                    foreach($room_redis['users'] as $k=>$v){
                        $roomUserArr = $this->getInfo($v['uid']);
                    }


                    $this->GameOver($room_id,$v);
                    Gateway::sendToClient($client_id,successSend('not_focas','出局',[]));//roomout
                    Gateway::sendToGroup($room_id,successSend('nonuse_focas','未使用福卡出局',['msg'=>$roomUserArr['nick_name'].'未使用福卡','out'=>$roomUserArr]));//focas
                }
                if($status == 1){
                    //有福卡
                    $room_redis['users'][$k]['status'] = 1;
                    $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);
                    $roomUserArr = [];
                    foreach($room_redis['users'] as $k=>$v){
                        $roomUserArr = $this->getInfo($v['uid']);
                    }
                    Gateway::sendToGroup($room_id,successSend('use_focas','复活',$roomUserArr));//focas


                }else{
                    $room_redis['users'][$k]['status'] = 2;
                    $room_redis['users'][$k]['not_use'] = 1;
                    $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);

                    # 修改订单状态 （判断游戏后修改）
                    $session = Gateway::getSession($client_id);
                    Db::name('shop_order')->where('ordersn',$session['ordersn'])->update(['playgame'=>1,'status'=>2]);
                    /*$order = OrderModel::getOrdersnInfo($session['ordersn']);
                    UserLevelModel::commssion($order);*/
                    $this->focas_porfit($session['uid']);

                    Gateway::leaveGroup($client_id,$room_id);

                    $roomUserArr = [];
                    foreach($room_redis['users'] as $k=>$v){
                        $roomUserArr = $this->getInfo($v['uid']);
                    }

                    $this->GameOver($room_id,$v);
                    Gateway::sendToClient($client_id,successSend('out','出局',[]));//roomout
                    Gateway::sendToGroup($room_id,successSend('nonuse_focas','未使用福卡出局',['msg'=>$roomUserArr['nick_name'].'未使用福卡','out'=>$roomUserArr]));//focas
                }

                return false;
            }
        }
    }


    public function RoomOut($client_id){
        //先查询是否正在游戏
        $info = $this->isPlayGame($client_id);

        if($info){
            $this->gameOverByOut($info['info'],$info['room_id'],$info['uid']);
            $this->roomchange();
            return false;
        }

    }

    /**
     * 退出房间
     * @param $client_id
     * @param $room_id
     */
    public function inRoomOut($client_id,$room_id){
        $info = $this->isPlayGame($client_id);
        if($info){
            $this->gameOverByOut($info['info'],$info['room_id'],$info['uid']);
            $this->roomchange();
            return false;
        }
        Gateway::leaveGroup($client_id,$room_id);
        echo 'Gateway::leaveGroup($client_id,$room_id);'."\n";
        $room_redis = $this->redis_hGet('1225blz_roominfo',$room_id);
        if(!$room_redis['users'])return false;

        $session = Gateway::getSession($client_id);
        foreach($room_redis['users'] as $k=>$v){
            if($session['uid'] == $v['uid']){
                unset($room_redis['users'][$k]);
            }
        }
        $this->redis_hSet('1225blz_roominfo',$room_id,$room_redis);
    }


    public function gameOverByOut($the_room,$room_id,$uid){
        if(!empty($the_room['users'])){


            foreach($the_room['users'] as $key=>$val){
                if($uid == $val['uid']){


                    $roomInfo = GameRoom::where('id',$room_id)->find();

                    if($roomInfo['status'] == 0){
                        return false;
                    }

                    //删除该用户
                    $the_room['users'][$key]['status'] = 2;
                    $this->redis_hSet('1225blz_roominfo',$room_id,$the_room);



                    # 修改订单状态 （判断游戏后修改）
                    $loginInfo = GameLoginLog::where('user_id',$uid)->order('id desc')->find();
                    if($loginInfo['ordersn']){
                        Db::name('shop_order')->where('ordersn',$loginInfo['ordersn'])->update(['playgame'=>1,'status'=>2]);
                        /*$order = OrderModel::getOrdersnInfo($loginInfo['ordersn']);
                        UserLevelModel::commssion($order);*/

                        //解绑房间
                        Gateway::leaveGroup($loginInfo['client_id'],$room_id);
                    }


                    //发送信息
                    $roomUserArr = [];
                    foreach($the_room['users'] as $k=>$v){
                        if($v['uid']){
                            $roomUserArr[] = $this->getInfo($v['uid']);
                        }
                    }
                    Gateway::sendToUid($uid,successSend('roomout','退出房间',[]));
                    Gateway::sendToGroup($room_id,successSend('userjoin','用户退房',$roomUserArr));

                    $this->GameOver($room_id,$the_room['users'][$key]);
                }else{
                    if($val['robot'] == 1){
                        $the_room['users'][$key]['status'] = 1;
                        $this->redis_hSet('1225blz_roominfo',$room_id,$the_room);
                    }
                }
            }
        }
    }

    public function isPlayGame($id)
    {

        //先查询是否正在游戏
        $loginInfo = GameLoginLog::where('client_id|user_id', $id)->order('id desc')->find();
        $arrr = GameRoom::select();
        $thisRoomRedis = [];
        $thisRoomInfo = [];
        $thisRoomId = [];
        foreach ($arrr as $k => $v) {
            $room_id = $v['id'];
            $the_room = $this->redis_hGet('1225blz_roominfo', $room_id);

            if (!empty($the_room['users'])) {

                foreach ($the_room['users'] as $key => $val) {
                    if ($loginInfo['user_id'] == $val['uid']) {
                        $thisRoomRedis = $the_room;
                        $thisRoomInfo = $v;
                        $thisRoomId = $v['id'];
                    }
                }
            }
        }

        if(!isset($thisRoomRedis['users']) || !$thisRoomInfo){
            return false;
        }
        $is_member = 0;
        foreach($thisRoomRedis['users'] as $key=>$val){
            if(isset($val['robot']) && $val['robot'] == 0){
                $is_member++;
            }
        }
        foreach($thisRoomRedis['users'] as $key=>$val){
            if ($loginInfo['user_id'] == $val['uid']) {
                if ($thisRoomInfo['status'] == 0) {
                    unset($thisRoomRedis['users'][$key]);
                    if ($is_member <= 1) {
                        unset($thisRoomRedis['thirty']);
                        GameRoom::where('id', $thisRoomId)->update(['status' => 0]);
                    }
                    $this->redis_hSet('1225blz_roominfo', $thisRoomId, $thisRoomRedis);
                    return false;
                }
                return ['room_id' => $thisRoomInfo['id'], 'info' => $thisRoomRedis, 'uid' => $val['uid']];
            }
        }


        return false;
    }
    public function workerStart(){
        User::where('robot',1)->update(['game_status'=>0]);
        GameRoom::where('status',1)->update(['status'=>0]);
        $arrr = GameRoom::select();
        foreach ($arrr as $k => $v) {
            $info = [
                'num'=>1,
                'users'=>[],
            ];
            $this->redis_hSet('1225blz_roominfo',$v['id'],$info);//存入redis
        }
    }


    private function focas_porfit($uid){
        MywalletLog::addLog($uid,10,3,'抽奖结束',16,1);
    }

    public function matching($uid,$room_id){
        $clientInfo = $this->getClientInfoByUid($uid);
        if(!$clientInfo)return;
        $session = Gateway::getSession($clientInfo['client_id']);

        // 踢出房间
        Gateway::leaveGroup($clientInfo['client_id'],$room_id);

        $orderMoney = Db::name('shop_order')->where('ordersn',$session['ordersn'])->sum('total');
        $arrr = GameRoom::where('money',$orderMoney)->where('status',0)->select()->toArray();
        if(empty($arrr)){
            #@没房退出到房间列表 roomout
            Gateway::sendToUid($uid,successSend('roomout','退出房间',[]));
        }else{
            #@ 有房跳到该房间 roomjump
            $keys = array_rand($arrr,1);
            Gateway::sendToUid($uid,successSend('roomjump','跳转房间',['room_id'=>$arrr[$keys]['id'],'ordersn'=>$session['ordersn']]));
        }

    }

}